package com.kld.shop.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kld.cms.api.ISysAdService;
import com.kld.cms.po.SysAd;
import com.kld.common.framework.dto.ResultMsg;
import com.kld.common.framework.page.PageInfoResult;
import com.kld.common.util.CreateFileName;
import com.kld.shop.controller.base.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by njh on 2015/10/29 0029.
 */

@Controller
@RequestMapping("/admin/ad")
public class SysAdController extends BaseController {

    @Resource
    private ISysAdService sysAdService;

    @RequestMapping("/adList")
    public String AdList(){
        return "admin/ad/adList";
    }

    /**
     * 得到广告列表
     * @return
     */
    @ResponseBody()
    @RequestMapping("/getAdList")
    public ResultMsg GetAdList(){
        PageHelper pageHelper = new PageHelper();
        pageHelper.startPage(getPageNum(), getPageSize());
        List<SysAd> adList =sysAdService.getAdList() ;
        PageInfo pageInfo = new PageInfo(adList);
        return PageInfoResult.PageInfoMsg(pageInfo);
    }

    /**
     * 编辑和添加广告
     * @param ad
     * @return
     */
    @ResponseBody()
    @RequestMapping("/editAd")
    public ResultMsg EditAd(SysAd ad){
               ResultMsg  result=new ResultMsg();
        if(ad.getId() == null){
            //添加广告
            SysAd ad1=sysAdService.getAdByCode(ad.getCode());
            if(ad1==null){
                ad.setOucode(getUserOuCode());
                ad.setCreater(getUserName());
                ad.setCreatetime(new Date());
                ad.setIsdel(0);
                int i=sysAdService.insertSelective(ad);
                if(i>0){
                    result.setResult(true);
                    result.setMsg("添加广告成功");
                }else{
                    result.setResult(false);
                    result.setMsg("添加广告失败");
                }
            }else{
                result.setResult(false);
                result.setMsg("对不起！广告编码已存在，请重新输入。");
            }
        }else {
            //编辑广告
            if(ad.getRemark()==null){
                ad.setRemark("");
            }
            int i=sysAdService.updateByPrimaryKeySelective(ad);
            if(i>0){
                result.setResult(true);
                result.setMsg("更新成功");
            }else {
                result.setResult(false);
                result.setMsg("更新失败");
            }
        }
        return  result;
    }

    /**
     * 批量删除广告
     * @param ids
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "/deleteAds",method = RequestMethod.POST)
    public ResultMsg DeleteAds(String ids){
        ResultMsg rmsg = new ResultMsg();
        try {
            String[] idList = ids.split(",");
            List<Integer> list = new ArrayList<Integer>();
            for(int i=0;i<idList.length;i++){
                list.add(Integer.valueOf(idList[i]));
            }
            int flag =sysAdService.deleteAdsByIds(list);
            if(flag>0){
                rmsg.setResult(true);
                rmsg.setMsg("删除成功");
            }else{
                rmsg.setResult(false);
                rmsg.setMsg("删除失败");
            }
        }catch (Exception e) {
            logger.info("批量删除广告失败:" + e.getMessage(), e);
            rmsg.setResult(false);
            rmsg.setMsg("操作失败" + e.getMessage());
        }
        return rmsg;
    }

    /**
     * 上传广告图片
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping("/uploadImg")
    public ResultMsg uploadPic(MultipartFile file){
        String msg="";

        boolean tag=false;
        String path=request.getSession().getServletContext().getRealPath("upload/ad");
//        System.out.println("图片地址："+path);
        //为上传的文件生成一个唯一名字
        String fileName="";
        String fileUrl="";
        if("".equals(file.getOriginalFilename())){
            fileName="default.png";
            fileUrl="/upload/ad/"+fileName;
        }else {
            fileName = CreateFileName.getFileName() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            File targetFile = new File(path, fileName);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            try {
                //保存文件
                file.transferTo(targetFile);
				/*String fileUrl=request.getContextPath()+"/upload/"+fileName;*/
                fileUrl = "/upload/ad/" + fileName;
                tag=true;
                msg=fileUrl;
//                System.out.println("文件路径：" + fileUrl);
//                System.out.println("文件上传成功");
            } catch (IllegalStateException e) {
                logger.info("上传广告失败:" + e.getMessage(), e);
            } catch (IOException e) {
                logger.info("上传广告失败:"+e.getMessage(),e);
            }
        }
        ResultMsg result=new ResultMsg();
        result.setResult(tag);
        result.setMsg(msg);
        return result;
    }
}
